﻿using CommonUtil;
using Ivi.Visa;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using VISAInstrument.Port;

namespace TKSamples
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private PortOperatorBase _portOperatorBase = null;

        #region Connect

        private void FormMain_Load(object sender, EventArgs e)
        {

        }

        private void btnConnet_Click(object sender, EventArgs e)
        {
            string IP = this.txtIP.Text.Trim();

            string IpRegex = @"^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$";

            if (!Regex.IsMatch(IP, IpRegex))
            {
                MessageBox.Show("IP地址不正确！");
                return;
            }

            if (!PortUltility.OpenIPAddress(IP, out string fullAddress))
            {
                MessageBox.Show("未找到设备!");
                return;
            }

            try
            {
                _portOperatorBase = new LANPortOperator(fullAddress);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化设备失败:{ex.Message}");
                return;
            }

            try
            {
                _portOperatorBase.Timeout = 2000;
                _portOperatorBase.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"连接设备失败:{ex.Message}");
                return;
            }

            EnabledControls(true);
            MessageBox.Show("连接成功！");
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            if (_portOperatorBase != null)
            {
                try
                {
                    _portOperatorBase.Close();
                    EnabledControls(false);
                }
                catch { }
                _portOperatorBase = null;
            }
        }

        private void EnabledControls(bool IsConnected)
        {
            this.btnConnet.Enabled = !IsConnected;
            this.btnDisconnect.Enabled = IsConnected;
            this.groupBoxOperator.Enabled = IsConnected;
        }

        #endregion

        #region Command

        private void btnWrite_Click(object sender, EventArgs e)
        {
            string CmdStr = this.txtCommand.Text.Trim();

            if (string.IsNullOrEmpty(CmdStr))
            {
                MessageBox.Show("请输入命令文本");
                return;
            }

            try
            {
                _portOperatorBase.WriteLine(CmdStr);
                ShowLog($"[Write][{CmdStr}][Success]");
            }
            catch
            {
                ShowLog($"[Write][{CmdStr}][ERROR]");
            }
        }

        private void btnReadString_Click(object sender, EventArgs e)
        {
            try
            {
                var result = _portOperatorBase.Read();
                ShowLog($"[Read][{result}][{result.Length}]");
            }
            catch (IOTimeoutException)
            {
                ShowLog($"[Read][ERROR:Timeout]");
            }
            catch (Exception ex)
            {
                ShowLog($"[Read][Exception:{ex.Message}]");
            }
        }

        private void btnReadBytes_Click(object sender, EventArgs e)
        {
            try
            {
                var result = _portOperatorBase.ReadBytes(2048);
                 var hexstr = ConvertHelper.ByteArrayToHexString(result);
                

                ShowLog($"[Read][{hexstr}][{result.Length}]");
            }
            catch (IOTimeoutException)
            {
                ShowLog($"[Read][ERROR:Timeout]");
            }
            catch (Exception ex)
            {
                ShowLog($"[Read][Exception:{ex.Message}]");
            }
        }

        private int[] Translate(byte[] result)
        {
            int Len = result.Length-7;
            int[] Datas = new int[Len];

            for(int i=0;i<Len;i++)
            {
                byte b = result[i + 6];

                if(b<0x80)
                {
                    Datas[i] = b;
                }
                else
                {
                    Datas[i] = -1 * ((byte)~b + 1);
                }
            }

            return Datas;
        }

        private void ShowLog(string log)
        {
            DateTime now = DateTime.Now;
            string info = $"\r\n[{now:hh:mm:ss}]{log}";

            this.txtLog.Text += info;
            if (this.txtLog.Text.Length > 80000)
            {
                this.txtLog.Text = "";
            }
            this.txtLog.SelectionStart = this.txtLog.Text.Length + 10;
            this.txtLog.SelectionLength = 0;
            this.txtLog.ScrollToCaret();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.txtLog.Text = "";
        }

        #endregion

       
    }
}
